What is esquery?
The esquery npm package is a tool for querying the abstract syntax tree (AST) of ECMAScript (JavaScript) code. It allows developers to find specific nodes within the AST using a CSS-like query syntax, making it easier to analyze and manipulate code structure programmatically.
What are esquery's main functionalities?
Selecting nodes by type
This feature allows you to select all nodes of a specific type, such as all function declarations in the AST. The code sample demonstrates how to select all function declaration nodes.
esquery(ast, 'FunctionDeclaration');
Selecting nodes by attribute
You can select nodes based on their attributes, such as selecting all nodes where the name attribute is 'myFunction'. The code sample shows how to select nodes with a specific name.
esquery(ast, '[name="myFunction"]');
Pseudo-classes for node selection
Esquery supports pseudo-classes for more complex queries, such as selecting the second child node of every matched set. The code sample demonstrates selecting the second child node.
esquery(ast, ':nth-child(2)');
Other packages similar to esquery
jscodeshift
jscodeshift is a toolkit for running codemods over multiple JavaScript or TypeScript files. It uses a different approach than esquery by providing a more extensive API for transforming the AST but also supports querying the AST in a way similar to esquery.
acorn
acorn is a fast, small JavaScript parser that generates an abstract syntax tree (AST). While it doesn't offer querying capabilities like esquery, it's often used in conjunction with other tools to analyze and manipulate JavaScript code.
estraverse
estraverse is a simple but powerful library for traversing and optionally modifying the AST of ECMAScript code. It doesn't use a query language like esquery but provides a programmatic way to navigate and manipulate nodes in the AST.